package com.food.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import com.food.dao.service.FooddetailService;
import com.food.dao.service.FoodsaveService;
import com.food.dao.service.RecipeService;
import com.food.dao.service.StepService;
import com.food.model.Fooddetail;
import com.food.model.Foodsave;
import com.food.model.Member;
import com.food.model.Recipe;
import com.food.model.Step;


@WebServlet("/recipe/RecipeInsertServlet")
public class RecipeInsertServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			processMultipart(request, response);
		} else {
			//errorMsgs.put("errMultipart" , "���O Multipart ���");
			//RequestDispatcher rd = request
			//		.getRequestDispatcher("InsertRecord/insertBLOBError.jsp");
			//rd.forward(request, response);
			//return;
		}

	}

	private void processMultipart(HttpServletRequest req,
			HttpServletResponse res) throws ServletException, IOException {
		
		
		String step_Num = "";
		Map<String,Map> step_map = new HashMap<String, Map>();
		Map<String,Object> step_sub_map = new HashMap<String, Object>();
		Fooddetail fooddetail = new Fooddetail();
		req.setCharacterEncoding("UTF-8");
		HttpSession session = req.getSession();
		Member member = (Member)session.getAttribute("user");
//		req.setAttribute("ErrMsg", errorMsgs);
//		session.setAttribute("ErrMsg", errorMsgs);
		try {
			String  rname = ""; 
			String  rintroduce = "";
			String  countryStr = "";
			String  step="";
			int  countryid = 0;
			String rtrick = "";
			String pathName = "";
			String sword = "";
			String fsidStr = "";
			String fdname = "";
			String fdunit = "";
			int fsid = 0;
			int sizeInBytes = 0 ;
			InputStream is = null ;
			int sizeInBytesStep = 0 ;
			InputStream isStep = null ; 
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = upload.parseRequest(req);
			Iterator<FileItem> itor = items.iterator();
			int key=-1;
			
			
			while (itor.hasNext()) {
				FileItem fitem =  itor.next();
				if (fitem.isFormField()) {
					System.out.println("if (fitem.isFormField())");
					String fldName = fitem.getFieldName();
					if (fldName.equals("rname")){
						rname = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
		                System.out.println(rname);
		                if (rname == null || rname.trim().length() == 0) {
		                	//System.out.println("BookInsertServlet.java, title Error");
		                } else {
		                	req.setAttribute("rname", rname);
		                }
					} else if (fldName.equals("rintroduce")){
						rintroduce = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						if (rintroduce == null || rintroduce.trim().length() == 0) {
						} else {
		                	req.setAttribute("rintroduce", rintroduce);
		                }
					} else if (fldName.equals("rtrick")){
						rtrick = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
		                req.setAttribute("rtrick", rtrick);
		                
				} 
					else if (fldName.equals("countryid")){
						countryStr = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						if (countryStr == null || countryStr.trim().length() == 0) {
		                } else {
		                	try {
		                		countryid = Integer.parseInt(countryStr);
		                		Recipe r = new Recipe();
				    			r.setMbid(member.getMbid());/////////記得getmbid
				    			r.setRname(rname);
				    			r.setRintroduce(rintroduce);
				    			r.setCountryid(countryid);
				    			r.setRtrick(rtrick);
				    			java.util.Date ud = new java.util.Date();
				    			java.sql.Date rdate= new java.sql.Date(ud.getTime());
				    			r.setRdate(rdate);
				    			
				    			RecipeService  service = new RecipeService();
				    			key = service.insertRecipe(r, is, sizeInBytes);
				    			System.out.println(key);
							} catch(NumberFormatException e) {
							}    
		                }						
						req.setAttribute("countryid", countryStr);
					}
					else if (fldName.equals("fsid")){
						fsidStr = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						if(!fsidStr.equals("品項")){
						fsid = Integer.parseInt(fsidStr);
						req.setAttribute("fsid", fsid);
						Foodsave foodsave = new Foodsave();
						foodsave.setRid(key);
						foodsave.setFsid(fsid);
						FoodsaveService foodsaveService = new FoodsaveService();
						foodsaveService.insertFoodsave(foodsave);
						}
		                
				} 
					else if (fldName.equals("step")){												
						
						step = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						req.setAttribute("step", step);
						System.out.println(step);
						//做一個bean
						Step s=new Step();
						s.setSnumber(Integer.parseInt(step));
						
						//做一個Map加入bean
						step_sub_map = new HashMap<String, Object>();
						
						step_Num= step;
						step_sub_map.put("bean",s);
						step_map.put(step,step_sub_map);
					} else if (fldName.equals("sword")){
						sword = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						req.setAttribute("sword", sword);
												
					} 
					else if (fldName.equals("fdname")){
						fdname = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						req.setAttribute("fdname", fdname);
						fooddetail.setFdname(fdname);						
					} 
					else if (fldName.equals("fdunit")){
						fdunit = new String(fitem.getString().getBytes("ISO-8859-1"), "UTF-8");
						req.setAttribute("fdunit", fdunit);
						if(fdname.trim().length()!=0 || fdunit.trim().length()!=0){
						fooddetail.setRid(key);
						fooddetail.setFdunit(fdunit);	
						FooddetailService fooddetailService = new FooddetailService();
						fooddetailService.insertFoodDetail(fooddetail);
						}
					} 
				}
				else{				
					System.out.println("走圖片else");
					String fieldName = fitem.getFieldName();
					System.out.println(fieldName);
					if(fieldName.equals("rimg"))
					{
						pathName = fitem.getName();  
						if (pathName != null && pathName.trim().length() > 0) {
							System.out.println("有圖片路徑");
							String contentType = fitem.getContentType();  
							sizeInBytes = (int)fitem.getSize();   
							is = fitem.getInputStream();
						} else {
						}
						
					}
					
					else if(fieldName.equals("simg")){
						
						
						System.out.println("子圖片路徑");
						String contentType = fitem.getContentType();  
						sizeInBytesStep = (int)fitem.getSize(); 
						
						isStep = fitem.getInputStream();
						step_sub_map = step_map.get(step);
						Step s =(Step)step_sub_map.get("bean");
						if(sizeInBytesStep!=0){
						s.setIs(isStep);
						s.setSize(sizeInBytesStep);
						}
						System.out.println(isStep);
						System.out.println(sizeInBytesStep);
						
//						step_sub_map.put("img",isStep);
//						step_sub_map.put("size",sizeInBytesStep);
						
						//step_sub_map = step_map.get(step);
						//Step s_real =(Step)step_sub_map.get("bean");
						if(sword.trim().length()!=0 || sizeInBytesStep!=0){
						s.setSword(sword);

						s.setRid(key);
						StepService stepService = new StepService();
						System.out.println("hhhhhhhhhhhhhhhh");
						stepService.insertStep(s);
						}

					}
					
				}
			}

			
			
		
			Set<String> temp_key= step_map.keySet();
			for(String temp_no:temp_key)
			{
				System.out.println(".....................");
				System.out.println(temp_no);
				step_sub_map = step_map.get(step);
//				Step s =(Step)step_sub_map.get("bean");
//				s.setRid(key);
//				StepService stepService = new StepService();
				//stepService.insertStep(s);
				
//				Map temp_map = step_map.get(temp_no);
//				Set<String> temp_sub_key = temp_map.keySet();
//				for(String temp_sub_no:temp_sub_key)
//				{
//					System.out.println("........");
//					System.out.println(temp_sub_no);
//					System.out.println(temp_map.get(temp_sub_no));
//					Step s = new Step();	
//					s.setRid(key);
//					if(temp_sub_no.equals("img"))
//					s.setIs();
//					
//				}
					
			}
			
			String path = req.getContextPath();
			res.sendRedirect(res.encodeRedirectURL(path+"/index.jsp"));
			return;
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher rd = req.getRequestDispatcher("/recipe/writerecipe.jsp");
			rd.forward(req, res);
		}
	}
	
}
